package com.lujianfei.mqtt.login.mvvm

import androidx.lifecycle.LiveData
import com.blankj.utilcode.util.ToastUtils
import com.lujianfei.mqtt.ktx.SingleLiveData
import com.lujianfei.mqtt.net.config.onError
import com.lujianfei.mqtt.net.config.onOK
import dagger.hilt.android.scopes.ViewModelScoped
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2024/4/15 16:26
 * @Description: 登录模块相关的 APi 仓库  类实现
 */
@ViewModelScoped
class LoginRepository @Inject constructor(private val service: LoginService) : ILoginRepository {
  /**
   * 手机号是否注册过
   */
  private val _registerRsp = SingleLiveData<RegisterRsp?>()
  override val registerRsp: LiveData<RegisterRsp?>
    get() = _registerRsp

  /**
   * 登陆请求
   */
  private val _loginRsp = SingleLiveData<UserInfo?>()
  override val loginRsp: LiveData<UserInfo?>
    get() = _loginRsp

  /**
   * 校验手机号是否注册、合法
   * @param account String -- 手机号
   */
  override suspend fun checkRegister(account: String) {
    kotlin.runCatching {
      service.isRegister(account).data
    }.onSuccess {
      _registerRsp.value = it
    }.onFailure {
      _registerRsp.value = null
    }
  }

  /**
   * 手机号合法的基础上，调用登录，获取登录结果token
   * @param body LoginReq -- 登录模块相关的请求 数据类
   */
  override suspend fun requestLogin(body: LoginReq) {
    kotlin.runCatching {
      service.login(body)
    }.onSuccess {
      // 这里通过 code 区分 是否拿到数据
      it.onOK { _, data, _ -> _loginRsp.value = data }
        .onError { _, message ->
        _loginRsp.value = null
        ToastUtils.showLong(message)
      }

    }.onFailure {
      _loginRsp.value = null
      ToastUtils.showLong(it.message)
    }
  }
}